<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px"
     style="display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, auto)); gap: 10px 20px; padding: 10px 0;"
     >
      <el-form-item label="维修单编号" prop="repairCode" style="margin-bottom: 5; white-space: nowrap;">
        <el-input
          v-model="queryParams.repairCode"
          placeholder="请输入维修单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="维修单名称" prop="repairName" style="margin-bottom: 5; white-space: nowrap;">
        <el-input
          v-model="queryParams.repairName"
          placeholder="请输入维修单名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备编码" prop="machineryCode" style="margin-bottom: 5; white-space: nowrap;">
        <el-input
          v-model="queryParams.machineryCode"
          placeholder="请输入设备编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="machineryName" style="margin-bottom: 5; white-space: nowrap;">
        <el-input
          v-model="queryParams.machineryName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="维修结果" prop="repairResult" style="margin-bottom: 5; white-space: nowrap;">
        <el-input
          v-model="queryParams.repairResult"
          placeholder="请输入维修结果"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单据状态" prop="status" style="margin-bottom: 5; white-space: nowrap;">
        <el-input
          v-model="queryParams.status"
          placeholder="请输入单据状态"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ls1:machineRepair:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ls1:machineRepair:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ls1:machineRepair:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ls1:machineRepair:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="machineRepairList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="维修单ID" align="center" prop="repairId" />
      <el-table-column label="维修单编号" align="center" prop="repairCode" />
      <el-table-column label="维修单名称" align="center" prop="repairName" />
      <el-table-column label="设备编码" align="center" prop="machineryCode" />
      <el-table-column label="设备名称" align="center" prop="machineryName" />
      <el-table-column label="报修日期" align="center" prop="requireDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.requireDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维修完成日期" align="center" prop="finishDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.finishDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="验收日期" align="center" prop="confirmDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.confirmDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维修结果" align="center" prop="repairResult" />
      <el-table-column label="维修人员" align="center" prop="acceptedBy" />
      <el-table-column label="验收人员" align="center" prop="confirmBy" />
      <el-table-column label="单据状态" align="center" prop="status" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['ls1:machineRepair:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['ls1:machineRepair:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

  <!-- 添加或修改设备维修单对话框（核心修改：替换下部分内容为子组件） -->
    <el-dialog :title="title" v-model="open" width="1300px" append-to-body>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="维修单编号" prop="repairCode">
            <el-input v-model="form.repairCode" placeholder="请输入维修单编号" style="width: 200px; display: inline-block;" />
            <el-switch v-model="autoGenerate" style="margin-left: 10px;" />
            <span style="margin-left: 5px;">自动生成</span>
          </el-form-item>
          <el-form-item label="维修单名称" prop="repairName">
            <el-input v-model="form.repairName" placeholder="请输入维修单名称" />
          </el-form-item>
          <el-form-item label="设备编码" prop="machineryCode">
            <el-input v-model="form.machineryCode" placeholder="请输入设备编码" style="width: 200px; display: inline-block;" />
            <el-button type="primary" style="margin-left: 5px;" >搜 索</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备名称" prop="machineryName">
            <el-input v-model="form.machineryName" placeholder="请输入设备名称" />
          </el-form-item>
          <el-form-item label="品牌" prop="machineryBrand">
            <el-input v-model="form.machineryBrand" placeholder="请输入品牌" />
          </el-form-item>
          <el-form-item label="报修日期" prop="requireDate">
            <el-date-picker clearable
              v-model="form.requireDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择报修日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
      </el-form-item>

      <!-- 核心修改1：移除原有的维修内容表格/分页/弹窗，替换为RepairLine子组件 -->
      <el-divider content-position="center">维修内容</el-divider>
      <!-- 传递repairId给子组件：修改时从form取，新增时初始为null -->
      <!-- 主组件中修改子组件引用 -->
       <!-- 主组件中添加调试打印 -->
      <RepairLine 
        :current-repair-id="form.repairId" 
        v-if="form.repairId"  
      ></RepairLine>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">提 交</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="MachineRepair">
import { listMachineRepair, getMachineRepair, delMachineRepair, addMachineRepair, updateMachineRepair } from "@/api/ls1/machineRepair"
import { ref, reactive, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import RepairLine from '@/views/repairLine/repairLine/index.vue'
import { TRUE } from "sass"

const { proxy } = getCurrentInstance()

const machineRepairList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const showAddRepairItemDialog = ref(false)
const repairItemRef = ref(null)
const repairitems = ref([])
const currentEditItem = ref(null)
const autoGenerate = ref(false)
const repairContent = ref([])
// 3. 选中的维修项（用于批量删除）
const selectedRepairItems = ref([])
// 4. 维修单行表单数据（reactive声明复杂对象）
const repairItemForm = reactive({
  projectName: '',
  faultDescription: '',
  faultResource: '',
  repairSituation: ''
})


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    repairCode: null,
    repairName: null,
    machineryCode: null,
    machineryName: null,
    repairResult: null,
    status: null,
  },
  rules: {
    repairCode: [
      { required: true, message: "维修单编号不能为空", trigger: "blur" }
    ],
    repairName: [
      { required: true, message: "维修单名称不能为空", trigger: "blur" }
    ],
    machineryCode: [
      { required: true, message: "设备编码不能为空", trigger: "blur" }
    ],
    machineryName: [
      { required: true, message: "设备名称不能为空", trigger: "blur" }
    ],
    requireDate: [
      { required: true, message: "报修日期不能为空", trigger: "blur" }
    ],
    finishDate: [
      { required: true, message: "维修完成日期不能为空", trigger: "blur" }
    ],
    confirmDate: [
      { required: true, message: "验收日期不能为空", trigger: "blur" }
    ],
    repairResult: [
      { required: true, message: "维修结果不能为空", trigger: "blur" }
    ],
    acceptedBy: [
      { required: true, message: "维修人员不能为空", trigger: "blur" }
    ],
    confirmBy: [
      { required: true, message: "验收人员不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "单据状态不能为空", trigger: "change" }
    ],
    projectName: [
      { required: true, message: '项目名称不能为空', trigger: 'blur' }
    ],
    faultDescription: [
      { required: true, message: '故障描述不能为空', trigger: 'blur' }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询设备维修单列表 */
function getList() {
  loading.value = true
  listMachineRepair(queryParams.value).then(response => {
    machineRepairList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    repairId: null,
    repairCode: null,
    repairName: null,
    machineryId: null,
    machineryCode: null,
    machineryName: null,
    machineryBrand: null,
    machinerySpec: null,
    machineryTypeId: null,
    requireDate: null,
    finishDate: null,
    confirmDate: null,
    repairResult: null,
    acceptedBy: null,
    confirmBy: null,
    status: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("machineRepairRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.repairId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加设备维修单"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _repairId = row.repairId || ids.value
  getMachineRepair(_repairId).then(response => {
    console.log("后端返回的维修单数据：", response.data); // 新增打印
    form.value = response.data
    open.value = true
    title.value = "修改设备维修单"
  },
  )
}


/** 提交按钮（核心优化：新增维修单后同步repairId给子组件） */
function submitForm() {
  // 修复：原代码引用的"machineRepairRef"未定义，需给el-form加ref
  // 先给主弹窗的el-form添加ref="machineRepairRef"（见下方补充说明）
  proxy.$refs["machineRepairRef"].validate(valid => {
    if (valid) {
      if (form.value.repairId != null) {
        // 修改场景：已有repairId，直接更新
        updateMachineRepair(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        // 新增场景：提交后从后端获取repairId，同步给form（触发子组件更新）
        addMachineRepair(form.value).then(response => {
          // 假设后端返回的数据含repairId（如response.data.repairId）
          form.value.repairId = response.data.repairId // 同步repairId给子组件
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}
/** 删除按钮操作 */
function handleDelete(row) {
  const _repairIds = row.repairId || ids.value
  proxy.$modal.confirm('是否确认删除设备维修单编号为"' + _repairIds + '"的数据项？').then(function() {
    return delMachineRepair(_repairIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('ls1/machineRepair/export', {
    ...queryParams.value
  }, `machineRepair_${new Date().getTime()}.xlsx`)
}

getList()
// 6. 提交维修单行（核心：将表单数据添加到表格）
const submitRepairItem = () => {
  proxy.$refs.repairItemRef.validate((valid) => {
    if (valid) {
      // 将表单数据添加到表格数据源
      repairContent.value.push({ ...repairItemForm })
      // 更新分页总数
      total.value = repairContent.value.length
      // 关闭弹窗+重置表单
      showAddRepairItemDialog.value = false
      resetRepairItemForm()
      ElMessage.success('维修项添加成功')
    }
  })
}

// 7. 重置维修单行表单
const resetRepairItemForm = () => {
  repairItemForm.projectName = ''
  repairItemForm.faultDescription = ''
  repairItemForm.faultResource = ''
  repairItemForm.repairSituation = ''
  proxy.$refs.repairItemForm?.resetFields()
}

// 8. 处理维修项选中（用于批量删除）
const handleRepairItemSelection = (selection) => {
  selectedRepairItems.value = selection
}

// 9. 批量删除维修项
const handleDeleteRepairItem = () => {
  if (selectedRepairItems.value.length === 0) {
    ElMessage.warning('请先选择要删除的维修项')
    return
  }
  ElMessageBox.confirm('确定删除选中的维修项？', '提示', { type: 'warning' })
    .then(() => {
      // 过滤掉选中的项
      const selectedIds = selectedRepairItems.value.map(item => item.id);
      repairContent.value = repairContent.value.filter(
        item => !selectedIds.includes(item.id)
      )
      total.value = repairContent.value.length;
      selectedRepairItems.value = []; // 清空选中的项，防止残留
      ElMessage.success('删除成功')
    })
}

// 10. 编辑维修项（可选，完善功能）
const handleEditRepairItem = (row) => {
  // 将表格行数据回显到表单
  repairItemForm.projectName = row.projectName
  repairItemForm.faultDescription = row.faultDescription
  repairItemForm.faultResource = row.faultResource
  repairItemForm.repairSituation = row.repairSituation
  isEditing.value = true;
  currentEditItemId.value = row.id; 
  // 打开弹窗
  showAddRepairItemDialog.value = true
}
</script>
